package org.lemon.db.store;

/**
 * @since 2024-12-11 20:07
 */
public class LogIterator {
    private FileManager fileManager;
    private BlockId blockId;
    private Page logPage;
    private int currentPosition;
    private int boundary;

    public LogIterator(FileManager fileManager, BlockId blockId) {
        this.fileManager = fileManager;
        this.blockId = blockId;
        this.logPage = Page.create(fileManager.getBlockSize());
        this.moveToBlock(blockId);
    }

    private void moveToBlock(BlockId blockId){
        fileManager.read(blockId,logPage);
        this.boundary = logPage.getInt(0);
        this.currentPosition = this.boundary;
    }

    public boolean hasNext(){
        //如果当前blockId = {BlockId@2261} 偏移位置小于区块大那么还有数据可以从当前区块读取
        //如果当前区块数据已经全部读完，但是区块号不为0，那么可以读取前面区块获得老的日志数据
        return currentPosition < fileManager.getBlockSize() || blockId.getBlkNum() > 0;
    }

    public byte[] next(){
        if(currentPosition == fileManager.getBlockSize()){
            this.blockId = new BlockId(blockId.getFileName(), blockId.getBlkNum() - 1) ;
            moveToBlock(blockId);
        }
        byte[] bytes = logPage.getBytes(currentPosition);
        currentPosition += logPage.blen(bytes);
        return bytes;
    }
}
